package com.tianci.appstore.ui.list.download;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

import com.coocaa.x.framework.utils.LogUtils;
import com.tianci.appstore.R;
import com.tianci.appstore.controller.manager.DownloadManagerController;
import com.tianci.appstore.controller.manager.DownloadManagerController.ACTION;
import com.tianci.appstore.ui.SkinManager;
import com.tianci.appstore.ui.data.SkyAppBaseData;
import com.tianci.appstore.ui.data.SkyAppDetailData.AppAction;
import com.tianci.appstore.ui.data.SkyAppDetailData.AppStatus;
import com.tianci.appstore.ui.data.SkyListAppData;
import com.tianci.appstore.ui.data.SkyListAppData.ListType;
import com.tianci.appstore.ui.data.SkyListProgressData;
import com.tianci.appstore.ui.detail.AppDownloadListener;
import com.tianci.appstore.ui.dialog.CommonAppOpDialog;
import com.tianci.appstore.ui.list.ListFlipper;
import com.tianci.appstore.ui.list.ListProgressBlock;
import com.tianci.appstore.ui.list.ListStatusBlock;
import com.tianci.appstore.ui.list.manage.ManageBaseListView;
import com.tianci.appstore.ui.util.UICommon;
import com.tianci.appstore.ui.widget.ColorButton;
import com.tianci.appstore.ui.widget.OnButtonClickListener;
import com.tianci.appstore.ui.widget.SkyCustomLayout;
import com.tianci.appstore.utils.SkyConstants;

import java.util.ArrayList;
import java.util.List;

public class DownloadListView extends ManageBaseListView implements
        AppDownloadListener, DownloadListDataListener, OnButtonClickListener {
    //    private TextView activeTaskText;
    private Button pauseAllBtn;
    private static final int PAUSE_ALL_BTN_ID = -100;
    private static final int UPDATE_ACTIVE_COUNT = 4;
    private static final int UPDATE_SHOW_INFO = 5;
    private static final int HIDE_DIALOG = 6;

    public DownloadListView(Context context) {
        super(context, ListType.DOWNLOAD_LIST);
        // TODO Auto-generated constructor stub
        initTopRightLayout();
        initController();
        setLoadingVisible(true);
    }

    protected void initController() {
        DownloadManagerController.getInstance().init(this, this);
    }

    protected void initTopRightLayout() {
        LinearLayout rightTopLayout = new LinearLayout(mContext);
        rightTopLayout.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL);

        pauseAllBtn = UICommon.newButton(mContext, rightTopTextSize, R.color.btnColor);
        pauseAllBtn.setId(PAUSE_ALL_BTN_ID);
        pauseAllBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (v.getTag() != null) {
                    ACTION action = (ACTION) v.getTag();
                    DownloadManagerController.getInstance().handleAction(action, null);
                }
            }
        });
        pauseAllBtn.setText(R.string.pause_all);
        SkinManager.setBackground(pauseAllBtn, R.drawable.search_selector);
        //pauseAllBtn.setPadding(SkyConstants.Div(50), SkyConstants.Div(30), SkyConstants.Div(50), SkyConstants.Div(30));
        rightTopLayout.addView(pauseAllBtn);

        LayoutParams topRightParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.TOP | Gravity.RIGHT);
        topRightParams.setMargins(0, SkyConstants.Div(85), SkyConstants.Div(102), 0);
        this.addView(rightTopLayout, topRightParams);
    }


    @Override
    public void destroyController() {
        // TODO Auto-generated method stub
        DownloadManagerController.getInstance().destroy();
        super.destroyController();
    }

    protected Handler mainHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            switch (msg.what) {
                case UPDATE_LIST:
                    refreshDataList(msg.getData().getInt("activeCount"),
                            msg.getData().getInt("pauseCount"), msg.getData().getInt("otherCount"),
                            (List<SkyListAppData>) msg.obj);
                    break;
                case UPDATE_STATUS:
                    String appId = msg.getData().getString("appId");
                    AppStatus status = AppStatus.valueOf(msg.getData().getString("status"));
                    refreshStatus(appId, status);
                    break;
                case UPDATE_PERCENT:
                    String appId2 = msg.getData().getString("appId");
                    refreshPercent(appId2, msg.arg1);
                    break;
                case UPDATE_ACTIVE_COUNT:
                    refreshActiveCount(msg.getData().getInt("activeCount"),
                            msg.getData().getInt("pauseCount"), msg.getData().getInt("otherCount"));
                    break;
                case UPDATE_SHOW_INFO:
                    refreshShowInfo(msg.getData().getString("appId"), msg.getData().getString("showInfo"));
                    break;
                case HIDE_DIALOG:
                    if (dialog != null)
                        dialog.hide();
                default:
                    handleOtherMsg(msg);
                    break;
            }
            super.handleMessage(msg);
        }
    };

    protected void handleOtherMsg(Message msg) {

    }

    @Override
    public void onUpdateStatus(String appId, AppStatus status) {
        // TODO Auto-generated method stub
        Message msg = mainHandler.obtainMessage(UPDATE_STATUS);
        Bundle bundle = new Bundle();
        bundle.putString("appId", appId);
        bundle.putString("status", status.toString());
        msg.setData(bundle);
        mainHandler.sendMessage(msg);
    }

    protected void refreshStatus(String appId, AppStatus status) {
        for (int i = 0; i < ListFlipper.VIEW_PAGE_COUNT; i++) {
            SkyCustomLayout child = (SkyCustomLayout) listFlipper.getChildAt(i);
            for (View view : child.getChildViews()) {
                ListStatusBlock block = (ListStatusBlock) view;
                if (block.getDataId() != null && block.getDataId().equals(appId)) {
                    block.updateStatus(status);
                    break;
                }
            }
        }
        if (dialog != null && dialog.isShowing()) {
            if (clickedData.getId().equals(appId)) {
                clickedAppStatus = status;
                dialog.refreshContent(getContentByStatus(status));
                if (clickedAppStatus == AppStatus.INSTALLING) {
                    dialog.setButtonVisible(0, false);
                    dialog.refreshButton(1, getContentByStatus(status),
                            R.drawable.btn_gray, R.drawable.btn_gray_focus, false);
                } else if (clickedAppStatus == AppStatus.INSTALLED) {
                    dialog.setButtonVisible(0, false);
                    dialog.setButtonVisible(1, false);
                    mainHandler.sendEmptyMessageDelayed(HIDE_DIALOG, 1000);
                } else {
                    dialog.setButtonVisible(0, true);
                    dialog.setButtonVisible(1, true);
                    dialog.refreshButton(getActionByStatus(status, 0), 0, false);
                    dialog.refreshButton(getActionByStatus(status, 1), 1, true);
                }
            }
        }
    }

    @Override
    public void onUpdatePercent(String appId, int percent) {
        // TODO Auto-generated method stub
        Message msg = mainHandler.obtainMessage(UPDATE_PERCENT);
        msg.arg1 = percent;
        Bundle bundle = new Bundle();
        bundle.putString("appId", appId);
        msg.setData(bundle);
        mainHandler.sendMessage(msg);
    }

    protected void refreshPercent(String appId, int percent) {
        for (int i = 0; i < ListFlipper.VIEW_PAGE_COUNT; i++) {
            SkyCustomLayout child = (SkyCustomLayout) listFlipper.getChildAt(i);
            for (View view : child.getChildViews()) {
                ListProgressBlock block = (ListProgressBlock) view;
                if (block.getDataId() != null && block.getDataId().equals(appId)) {
                    block.updateProgress(percent);
                    break;
                }
            }
        }
    }

    @Override
    public void onDownloadListLoaded(int activeCount, int pauseCount,
                                     int otherCount, List<SkyListProgressData> dataList) {
        // TODO Auto-generated method stub
        Message msg = mainHandler.obtainMessage(UPDATE_LIST);
        Bundle bundle = new Bundle();
        bundle.putInt("activeCount", activeCount);
        bundle.putInt("pauseCount", pauseCount);
        bundle.putInt("otherCount", otherCount);
        msg.setData(bundle);
        msg.obj = dataList;
        mainHandler.sendMessage(msg);
    }

    protected void refreshDataList(int activeCount, int pauseCount, int otherCount,
                                   List<SkyListAppData> dataList) {
        if (dataList == null || dataList.size() == 0) {
            setEmptyTipVisible(true, mContext.getResources().getString(R.string.no_downloading_task));
            setButtonEnabled(pauseAllBtn, false, R.string.no_downloading, null);
            mController.setDataList(new ArrayList<SkyListAppData>());
            return;
        }
        setLoadingVisible(false);
        setEmptyTipVisible(false, null);
        refreshActiveCount(activeCount, pauseCount, 0);
        if (lastFocusPageIndex != -1 && lastFocusIndex != -1) {
            mController.setDataList(dataList, lastFocusPageIndex, lastFocusIndex);
            lastFocusPageIndex = -1;
            lastFocusIndex = -1;
        } else {
            mController.setDataList(dataList);
            resetFocus();
        }
    }

    @Override
    public void onRefreshDownloadCount(int activeCount, int pauseCount, int otherCount) {
        // TODO Auto-generated method stub
        Message msg = mainHandler.obtainMessage(UPDATE_ACTIVE_COUNT);
        Bundle bundle = new Bundle();
        bundle.putInt("activeCount", activeCount);
        bundle.putInt("pauseCount", pauseCount);
        bundle.putInt("otherCount", otherCount);
        msg.setData(bundle);
        mainHandler.sendMessage(msg);
    }

    protected void refreshActiveCount(int activeCount, int pauseCount, int otherCount) {
        if (activeCount > 0) {
            setButtonEnabled(pauseAllBtn, true, R.string.pause_all, ACTION.PAUSE_ALL);
        } else {
            if (pauseCount > 0)
                setButtonEnabled(pauseAllBtn, true, R.string.start_all, ACTION.DOWNLOAD_ALL);
            else
                setButtonEnabled(pauseAllBtn, false, R.string.no_downloading, null);
        }
    }

    @Override
    public void onRefreshShowInfo(String appId, String showInfo) {
        // TODO Auto-generated method stub
        Message msg = mainHandler.obtainMessage(UPDATE_SHOW_INFO);
        Bundle data = new Bundle();
        data.putString("appId", appId);
        data.putString("showInfo", showInfo);
        msg.setData(data);
        mainHandler.sendMessage(msg);
    }

    private void refreshShowInfo(String appId, String showInfo) {
        for (int i = 0; i < ListFlipper.VIEW_PAGE_COUNT; i++) {
            SkyCustomLayout child = (SkyCustomLayout) listFlipper.getChildAt(i);
            for (View view : child.getChildViews()) {
                ListProgressBlock block = (ListProgressBlock) view;
                if (block.getDataId() != null && block.getDataId().equals(appId)) {
                    block.updateShowInfo(showInfo);
                    break;
                }
            }
        }
    }

    protected void setButtonEnabled(Button btn, boolean enabled, int strId, ACTION action) {
        btn.setEnabled(enabled);
        btn.setTag(action);
        if (enabled)
            btn.setAlpha(1.0f);
        else {
            btn.setAlpha(UICommon.disableAlpha);
            resetFocus();
        }
        btn.setText(strId);
        btn.setFocusable(enabled);
    }


    protected CommonAppOpDialog dialog;
    protected AppStatus clickedAppStatus;
    protected SkyListAppData clickedData;

    protected AppAction getActionByStatus(AppStatus status, int index) {
        AppAction action = AppAction.ACTION_NULL;
        switch (status) {
            case DOWNLOADING:
                if (index == 0)
                    action = AppAction.ACTION_CANCEL;
                else
                    action = AppAction.ACTION_PAUSE;
                break;
            case DOWNLOAD_PAUSED:
                if (index == 0)
                    action = AppAction.ACTION_CANCEL;
                else
                    action = AppAction.ACTION_CONTINUE;
                break;
            case DOWNLOADED:
                if (index == 0)
                    action = AppAction.ACTION_DELETE;
                else
                    action = AppAction.ACTION_INSTALL;
                break;
            case WAITING:
                if (index == 0)
                    action = AppAction.ACTION_CANCEL;
                else
                    action = AppAction.ACTION_PRIORITIZE;
                break;
        }
        return action;
    }

    protected String getContentByStatus(AppStatus status) {
        String content = "";
        switch (status) {
            case DOWNLOADING:
                content = mContext.getResources().getString(R.string.downloading_tip);
                break;
            case DOWNLOAD_PAUSED:
                content = mContext.getResources().getString(R.string.paused_tip);
                break;
            case DOWNLOADED:
                content = mContext.getResources().getString(R.string.downloaded_tip);
                break;
            case WAITING:
                content = mContext.getResources().getString(R.string.waiting_tip);
                break;
            case INSTALLING:
                content = mContext.getResources().getString(R.string.installing);
                break;
            case INSTALLED:
                content = mContext.getResources().getString(R.string.installed);
                break;
        }
        return content;
    }

    // 处理某应用点击事件
    @Override
    public void onBlockClicked(View v, SkyListAppData data, int index) {
        // TODO Auto-generated method stub
        lastFocusPageIndex = mController.getCurrentPageIndex();
        lastFocusIndex = index;
        clickedData = data;
        if (dialog == null) {
            dialog = new CommonAppOpDialog(mContext);
            dialog.setButtonClickListener(this);
        }
        clickedAppStatus = ((SkyListProgressData) data).getStatus();

        dialog.setData(data, getContentByStatus(clickedAppStatus));
        AppAction action = getActionByStatus(clickedAppStatus, 0);
        if (action == AppAction.ACTION_CANCEL) {
            ColorButton btn = new ColorButton(mContext, R.string.cancel_download,
                    R.drawable.btn_gray, R.drawable.btn_gray_focus);
            dialog.addButton(btn, 0, false);
        } else {
            dialog.addButton(action, 0, false);
        }
        dialog.addButton(getActionByStatus(clickedAppStatus, 1), 1, true);

        if (clickedAppStatus == AppStatus.INSTALLING) {
            dialog.setButtonVisible(0, false);
            dialog.refreshButton(1, getContentByStatus(clickedAppStatus),
                    R.drawable.btn_gray, R.drawable.btn_gray_focus, false);
        } else if (clickedAppStatus == AppStatus.INSTALLED) {
            dialog.setButtonVisible(0, false);
            dialog.setButtonVisible(1, false);
            mainHandler.sendEmptyMessageDelayed(HIDE_DIALOG, 1000);
        } else {
            dialog.setButtonVisible(0, true);
            dialog.setButtonVisible(1, true);
        }
        dialog.show();
    }

    // 处理弹出框button点击事件
    @Override
    public void onClick(int index) {
        // TODO Auto-generated method stub
        AppAction action = getActionByStatus(clickedAppStatus, index);
        if (action == AppAction.ACTION_PAUSE ||
                action == AppAction.ACTION_CONTINUE ||
                action == AppAction.ACTION_INSTALL ||
                action == AppAction.ACTION_DELETE ||
                action == AppAction.ACTION_CANCEL ||
                action == AppAction.ACTION_PRIORITIZE) {
            ACTION realAction = ACTION.PAUSE;
            if (action == AppAction.ACTION_CONTINUE)
                realAction = ACTION.START;
            else if (action == AppAction.ACTION_INSTALL)
                realAction = ACTION.INSTALL;
            else if (action == AppAction.ACTION_DELETE
                    || action == AppAction.ACTION_CANCEL)
                realAction = ACTION.DELETE;
            else if (action == AppAction.ACTION_PRIORITIZE)
                realAction = ACTION.TO_FIRST;
            LogUtils.d("hhhh", "send cmd to lyx, realAction = " + realAction);
            DownloadManagerController.getInstance().handleAction(realAction, (SkyListProgressData) clickedData);
        }
        dialog.hide();
    }

    @Override
    public void onItemAudioMatch(SkyAppBaseData data, int index) {
        ACTION action = ACTION.DELETE;
        DownloadManagerController.getInstance().handleAction(action, (SkyListProgressData) clickedData);
    }

}
